package com.honkentuber.chat;

import java.util.List;

import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

@PersistenceCapable(identityType = IdentityType.APPLICATION)
// @Unique(members={"roomId", "sequenceNumber"})
public class Message {
  @PrimaryKey
  @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
  private Key key;

  @Persistent
  private Key roomKey;

  @Persistent
  private long sequenceNumber;

  @Persistent
  private Key authorKey;

  @Persistent
  private String content;

  @Persistent
  private long timeMillis;

  public Message(long sequenceNumber, Key roomKey, Key authorKey,
      String content, long timeMillis) {
    this.sequenceNumber = sequenceNumber;
    this.roomKey = roomKey;
    this.authorKey = authorKey;
    this.content = content;
    this.timeMillis = timeMillis;
  }

  public Message(long key, Key roomId, Key authorKey, String content) {
    this(key, roomId, authorKey, content, System.currentTimeMillis());
  }

  public Key getKey() {
    return key;
  }

  public Key getRoomKey() {
    return roomKey;
  }

  public long getSequenceNumber() {
    return sequenceNumber;
  }

  public Key getAuthorKey() {
    return authorKey;
  }

  public String getContent() {
    return content;
  }

  public long getTimeMillis() {
    return timeMillis;
  }

  public String toString() {
    return roomKey + "|" + sequenceNumber + "|" + authorKey + "|" + content;
  }

  @SuppressWarnings("unchecked")
  public JSONObject toJson() {
    JSONObject jsonMsg = new JSONObject();
    jsonMsg.put("roomKey", KeyFactory.keyToString(roomKey));
    jsonMsg.put("seq", sequenceNumber);
    if (authorKey != null) {
      jsonMsg.put("authorKey", KeyFactory.keyToString(authorKey));
    }
    jsonMsg.put("content", content);
    jsonMsg.put("timeMillis", timeMillis);
    return jsonMsg;
  }

  @SuppressWarnings("unchecked")
  public static JSONArray toJsonArray(List<Message> msgs) {
    JSONArray jsonMsgs = new JSONArray();
    for (Message msg : msgs) {
      jsonMsgs.add(msg.toJson());
    }
    return jsonMsgs;
  }
}